//
//  RechargeViewController.m
//  ZYZB
//
//  Created by ENERGY on 2018/7/10.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "RechargeViewController.h"
#import "BankRechargeViewController.h"
@interface RechargeViewController ()<UITextFieldDelegate>
@property (nonatomic, strong)UITextField * moneyTextField;//充值
@end

@implementation RechargeViewController(networking)
//账户余额充值
- (void)rechargeData{
//    [self showprogressHUD];
    NSString * timeStr = [self currentTimeStr];
    //str
    NSDictionary * dic = @{
                           @"userName":[UserModel sharedInstanced].mobile,
                           @"reMoney":self.moneyTextField.text,
                           @"t":timeStr
                           };
    //sign
    NSDictionary * signDic = @{
                               @"userName":[UserModel sharedInstanced].mobile,
                               @"reMoney":self.moneyTextField.text,
                               @"t":timeStr,
                               @"merchantNo":@"80d709a97af1b8ab"
                               };
    SortMD5Code * md5Code = [[SortMD5Code alloc] init];
    NSString * jsonStr = [md5Code getJsonWithStrDic:dic withSignDic:signDic];
    NSData *postData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:@"http://120.78.157.132:82/index.php/doMoney/kjCash"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置请求方式
    request.HTTPMethod = @"POST";
    //设置请求参数
    request.HTTPBody = postData;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        [self hiddenProgressHUD];
        if (connectionError) {
            if (connectionError.code == -1001) {
                [self.view makeToast:@"请求网络超时，请稍后再试" duration:1 position:CSToastPositionCenter];
            }
        }else{
            NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];//data解析为dictionary
            if (!dictionary) {
                NSLog(@"数据缺失");
                return;
            }
            NSDictionary * jsonData = [md5Code getNSDictionaryData:dictionary];//解析为字典数据
            if ([jsonData[@"code"] isEqualToString:@"000000"]) {
                BankRechargeViewController * vc = [[BankRechargeViewController alloc] init];
                vc.webURLStr = [jsonData[@"body"] objectForKey:@"shabaction"];
                vc.bankNeedInfoDic = @{
                                       @"merchantNo":[jsonData[@"body"] objectForKey:@"merchantNo"],
                                       @"keyEnc":[jsonData[@"body"] objectForKey:@"keyEnc"],
                                       @"merOrderNo":[jsonData[@"body"] objectForKey:@"merOrderNo"],
                                       @"jsonEnc":[jsonData[@"body"] objectForKey:@"jsonEnc"],
                                       @"sign":[jsonData[@"body"] objectForKey:@"sign"]};
                vc.sessionID = jsonData[@"session"];
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                ShowMessage(jsonData[@"msg"]);
            }
        }
    }];
}
@end

@implementation RechargeViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"账户余额充值";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setUpViews];
}

- (void)setUpViews{
    UILabel * titleLab = [[UILabel alloc] initWithFrame:CGRectMake(18/WIDTH_6_SCALE, 16/WIDTH_6_SCALE, 150/WIDTH_6_SCALE, 13/WIDTH_6_SCALE)];
    [self label:titleLab withFont:DEF_FontSize_14 withText:@"请输入充值金额(元)" withTextColor:[UIColor blackColor] withTextAlignment:NSTextAlignmentLeft withView:self.view];
    UILabel * symbolLab = [[UILabel alloc] initWithFrame:CGRectMake(titleLab.left, titleLab.bottom + 47/WIDTH_6_SCALE, 17/WIDTH_6_SCALE, 22/WIDTH_6_SCALE)];
//    symbolLab.backgroundColor = [UIColor orangeColor];
    symbolLab.text = @"￥";
    symbolLab.textColor = [UIColor orangeColor];
    [self.view addSubview:symbolLab];
    //充值
    self.moneyTextField = [[UITextField alloc] initWithFrame:CGRectMake(symbolLab.right + 8/WIDTH_6_SCALE, symbolLab.top, SCREEN_WIDTH - symbolLab.right - 18/WIDTH_6_SCALE - 5/WIDTH_6_SCALE, symbolLab.height)];
    self.moneyTextField.font = [UIFont systemFontOfSize:25.0];
    self.moneyTextField.clearButtonMode = UITextFieldViewModeAlways;
    self.moneyTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.moneyTextField.delegate = self;
    [self.view addSubview:self.moneyTextField];
    //分割线
    UIView * lineView = [[UIView alloc] initWithFrame:CGRectMake(18/WIDTH_6_SCALE, self.moneyTextField.bottom + 10/WIDTH_6_SCALE, SCREEN_WIDTH - (18*2)/WIDTH_6_SCALE, 1/WIDTH_6_SCALE)];
    lineView.backgroundColor = getColor(grayBGColor);
    [self.view addSubview:lineView];
    //下一步
    UIButton * nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(28/WIDTH_6_SCALE, lineView.bottom + 55/WIDTH_6_SCALE, SCREEN_WIDTH - (28*2)/WIDTH_6_SCALE, 38/WIDTH_6_SCALE)];
    [nextBtn addTarget:self action:@selector(nextBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
    nextBtn.titleLabel.font = DEF_FontSize_14;
    [nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self button:nextBtn withBGColor:[UIColor orangeColor] withLayerBorderColor:nil withLayerBorderWith:0 withCornerRadius:6 withMasksToBounds:YES withViwe:self.view];
}
#pragma mark - action
- (void)nextBtnClick:(UIButton *)sender{
    NSLog(@"下一步");
    if ([self.moneyTextField.text intValue] > 0) {
        [self rechargeData];
    }
    
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    return [self validateNumber:string];
}
- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

@end
